package cn.arrow.note.validation.specific;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 特定值校验类
 *
 * @author zimo
 * @date 2021-07-30
 **/

public class SpecificValueValidator implements ConstraintValidator<SpecificValue, Object> {

    private String[] strValues;

    private int[] intValues;

    @Override
    public void initialize(SpecificValue specificValue) {
        strValues = specificValue.strValues();
        intValues = specificValue.intValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 校验单个字符串是否为指定值
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        }

        // 校验数字是否为指定值
        if (value instanceof Integer) {
            for (Integer i : intValues) {
                if (i.equals(value)) {
                    return true;
                }
            }
        }
        return false;
    }

}
